import { GlobalData } from '/store/state'
import { $event } from '/utils'

const backIcon = '/images/ico_title_back_black.png'

Component({
  properties: {
    text: { type: String, value: '' },
    icon: { type: String || Boolean, value: backIcon },
    autoWidth: { type: Boolean, value: false },
    /** 临时数据 */
    border: { type: Boolean, value: false },
    white: { type: Boolean, value: false },
  },
  data: {
    capsuleStyle: '',
    top: 0,
    height: 0,
  },
  lifetimes: {
    attached() {
      $event.on('after:boot', this, () => {
        this.getPosition()
      })
      this.getPosition()
    },
  },
  methods: {
    getPosition() {
      const position = GlobalData.menuRect
      const { height, top, width, right } = position
      const left = GlobalData.clientWidth - right
      let capsuleStyle = `top: ${top}px;height: ${height}px;left: ${
        !this.data.border ? 0 : left
      }px;`

      // 固定宽度
      const w = this.data.text ? width : width / 2
      if (!this.data.autoWidth) capsuleStyle += `width: ${w}px;`

      this.setData({ width, height, right, top, capsuleStyle })
    },
    goBack() {
      // 如果有自定义图标, 就拦截事件
      // if (this.data.icon !== backIcon) return this.triggerEvent('click')
      const pages = getCurrentPages()
      if (pages.length === 1) {
        wx.switchTab({ url: '/pages/feed/list/list' })
      } else {
        wx.navigateBack({ delta: 1 })
      }
    },
  },
})
